package com.hnu.highlynewapp.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author kLjSumi
 * @Date 2021/1/3
 */
@Component
public class OssUtil {
    private String endpoint = "oss-cn-shenzhen.aliyuncs.com";
    private String accessKeyId = "LTAI4GBGuWFQCnuc3pWtp4WN";
    private String accessKeySecret = "MWIhRezgIeHFWSS1XncAamSM7xaoYn";
    private String bucketName = "highlynew-app";
    private OSS ossClient = null;
    private InputStream inputStream = null;

    public String upload(MultipartFile file) throws IOException {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String fileName = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) +"/"+UUID.randomUUID().toString()+"."+ file.getOriginalFilename().split("\\.")[1];
        inputStream = new ByteArrayInputStream(file.getBytes());
        ossClient.putObject(bucketName, fileName, inputStream);
        String url = "http://" + bucketName + "." + endpoint + "/" + fileName;
        ossClient.shutdown();
        return url;
    }

    public List<String> upload(MultipartFile[] files) throws IOException {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        List<String> list = new ArrayList<>();

        for (MultipartFile file : files) {
            String[] split = file.getOriginalFilename().split(".");
            String fileName = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) +"/"+UUID.randomUUID().toString()+"."+ file.getOriginalFilename().split("\\.")[1];
            inputStream = new ByteArrayInputStream(file.getBytes());
            ossClient.putObject(bucketName, fileName, inputStream);
            String url = "http://" + bucketName + "." + endpoint + "/" + fileName;
            list.add(url);
        }
        ossClient.shutdown();
        return list;
    }

}
